package git.soulbgm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import git.soulbgm.mapper.SysConfigInfoMapper;
import git.soulbgm.pojo.SysConfigInfo;
import git.soulbgm.pojo.dto.SysConfigInfoDto;
import git.soulbgm.pojo.vo.SysConfigParamVo;
import git.soulbgm.service.SysConfigInfoService;
import git.soulbgm.service.SysConfigParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static git.soulbgm.common.MonitorConstants.*;

/**
 * 系统配置参数服务实现类
 *
 * @author SoulBGM
 * @date 2022/07/08 18:11
 */
@Service
public class SysConfigInfoServiceImpl extends ServiceImpl<SysConfigInfoMapper, SysConfigInfo> implements SysConfigInfoService {

    @Autowired
    private SysConfigParamService sysConfigParamService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean save(SysConfigInfoDto dto) {
        SysConfigInfo sysConfigInfo = new SysConfigInfo();
        sysConfigInfo.setName(dto.getName());
        sysConfigInfo.setValue(dto.getValue());
        sysConfigInfo.setType(dto.getType());
        sysConfigInfo.setRemark(dto.getRemark());
        boolean result = save(sysConfigInfo);
        List<SysConfigParamVo> param = dto.getParam();
        if (result && param != null && !param.isEmpty()) {
            result = sysConfigParamService.save(param, sysConfigInfo.getId());
        }
        return result;
    }

    @Override
    public String getSysConfig(String name) {
        SysConfigInfo info = getOne(new LambdaQueryWrapper<SysConfigInfo>().eq(SysConfigInfo::getName, name));
        if (info == null) {
            return null;
        }
        Integer type = info.getType();
        if (type == SYS_CONFIG_PARAM_VALUE) {
            return info.getValue();
        }
        List<SysConfigParamVo> list = sysConfigParamService.findByCode(info.getId());
        if (list.isEmpty()) {
            return "";
        }
        return sysConfigParamService.getJson(list, type);
    }

    @Override
    public boolean checkUnique(SysConfigInfo info) {
        return count(new LambdaQueryWrapper<SysConfigInfo>()
                .eq(SysConfigInfo::getName, info.getName())) == 0;
    }

}
